<?php
class AccesManager
{
  private $_db;
  private $_DureeAcces = 36000; //10h

  public function __construct($db)
  {
    $this->setDb($db);
  }

  public function add(Acces $acces) //Ajout un accès à la BDD
  {
    $q = $this->_db->prepare('INSERT INTO acces SET idRefTest = :idRefTest, idRefClasse = :idRefClasse, dateacces = :dateacces');

    $q->bindValue(':idRefTest', $acces->idRefTest(), PDO::PARAM_INT);
    $q->bindValue(':idRefClasse', $acces->idRefClasse(), PDO::PARAM_INT);
    $q->bindValue(':dateacces', $acces->dateacces());

    $q->execute();
  }

  public function delete(Acces $acces)
  {
    $this->_db->exec('DELETE FROM acces WHERE id = '.$acces->id());
  }

  public function get($id)
  {
    $id = (int) $id;

    $q = $this->_db->query('SELECT * FROM acces WHERE id = '.$id);
    $donnees = $q->fetch();
    return new Acces($donnees);
  }

  public function checkByClasse($id)
  {
    $id = (int) $id;
	$time10m = time() - $this->_DureeAcces;
	$time10p = time() + $this->_DureeAcces;
    $q = $this->_db->query('SELECT * FROM acces WHERE dateacces > '.$time10m.' AND dateacces < '.$time10p.' AND idRefClasse = '.$id);
    $donnees = $q->fetch();
	
	if($donnees != false){
    	return new Acces($donnees);
	} else {
		return false;
	}
  }
  
  public function check($idTest,$idClasse)
  {
    $idTest = (int) $idTest;
	$idClasse = (int) $idClasse;
	
	$time10m = time() - $this->_DureeAcces;
	$time10p = time() + $this->_DureeAcces;
    $q = $this->_db->query('SELECT * FROM acces WHERE dateacces > '.$time10m.' AND dateacces < '.$time10p.' AND idRefClasse = '.$idClasse.' AND idRefTest = '.$idTest);
    $donnees = $q->fetch();
	
	if($donnees != false){
    	return true;
	} else {
		return false;
	}
  }
  
  public function getList()
  {
    $acces = array();

    $q = $this->_db->query('SELECT * FROM acces ORDER BY id');

    while ($donnees = $q->fetch())
    {
      $acces[] = new Acces($donnees);
    }

    return $acces;
  }

  public function update(Acces $acces)
  {
    $q = $this->_db->prepare('UPDATE acces SET idRefTest = :idRefTest, idRefClasse = :idRefClasse, dateacces = :dateacces WHERE id = :id');

    $q->bindValue(':idRefTest', $acces->idRefTest(), PDO::PARAM_INT);
    $q->bindValue(':idRefClasse', $acces->idRefClasse(), PDO::PARAM_INT);
    $q->bindValue(':dateacces', $acces->dateacces());
    $q->bindValue(':id', $acces->id(), PDO::PARAM_INT);

    $q->execute();
  }

  public function setDb(PDO $db)
  {
    $this->_db = $db;
  }
}
?>